<template>
	<view class="com-toolbar">
		<view :style="{
			'visibility': visibleSync ? 'visible' : 'hidden'
		}" class="com-toolbar-mask" @tap="handleHide"></view>
		<view elevation="30px" class="com-toolbar-right y-flex" :style="{
			'transition-duration': duration + 'ms',
			'background-color': bgColor,
			'border-radius': pixelunit(radius),
			'top': pixelunit(top),
			'right': pixelunit(right),
			'width': pixelunit(popupWidth),
			'height': pixelunit(popupHeight),
			'opacity': visibleSync ? 1 : 0
		}">
			<slot></slot>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			top: {
				type: [String, Number],
				default: 0
			},
			right: {
				type: [String, Number],
				default: 0
			},
			width: {
				type: [String, Number],
				default: 0
			},
			radius: {
				type: [String, Number],
				default: 0
			},
			bgColor: {
				type: String,
				default: '#fff'
			},
			duration: {
				type: [String, Number],
				default: 200
			}
		},
		computed: {
			popupTop () {
				return uni.getSystemInfoSync().safeArea.top + uni.upx2px(100)
			},
			popupWidth () {
				return this.visibleSync ? this.width : 0
			},
			popupHeight () {
				return this.visibleSync ? this.height : 0
			},
			height () {
				return this.count * 100
			}
		},
		data () {
			return {
				visibleSync: false,
				count: 0
			}
		},
		created() {
			this.visibleSync = this.visible
		},
		mounted () {
			this.$nextTick(function () {
				const arr = this.handleGetChildrens()
				this.count = arr.length
			})
		},
		methods: {
			pixelunit (size) {
				const text = size.toString()
				return text.indexOf('px') > -1 ? text : text + 'rpx'
			},
			handleHide () {
				this.visibleSync = false
				this.$emit('hide')
				this.$emit('update:visible', false)
			},
			handleGetChildrens () {
				let arr = []
				let childs = ['ComToolbarItem']
				const dowhile = (children) => {
					if ( Object.prototype.toString(children) == '[object Object]' ) {
						children.forEach(child => {
							if ( childs.indexOf(child.$options.name) > -1 ) {
								arr.push(child)
							}
							if ( child.$children && child.$children.length > 0 ) {
								dowhile(child.$children)
							}
						})
					}
				}
				dowhile(this.$children)
				return arr;
			}
		},
		watch: {
			visible (newVal) {
				this.visibleSync = newVal
			}
		}
	}
</script>

<style>
	.com-toolbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* #ifndef APP-NVUE */
		pointer-events: none;
		/* #endif */
		
	}
	.com-toolbar-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* #ifndef APP-NVUE */
		pointer-events: auto;
		/* #endif */
	}
	.com-toolbar-right {
		position: absolute;
		right: 0;
		top: 0;
		width: 0;
		height: 0;
		transition-property: height, width, background-color, opacity;
		/* #ifndef APP-NVUE */
		pointer-events: auto;
		box-shadow: 0 15px 30px rgba(0,0,0,.2);
		/* #endif */
	}
</style>